<template>
  <div class="show">
    <div>效果</div>
    <div class="show-box" ref="ShowBox"></div>
  </div>
</template>

<script>
export default {
  name: 'Show',
  props: {
    data: {
      type: String,
      default: '',
    },
  },
  methods: {
    getSource(type) {
      const reg = new RegExp(`<${type}[^>]*>`)
      let code = this.data
      let matches = code.match(reg)
      if(matches) {
        let tag = matches[0]
        return code.slice(code.indexOf(tag) + tag.length, code.lastIndexOf(`</${type}>`))
      }
    },
    run() {
      const template = this.getSource('template')
      const script = this.getSource('script').replace(/export default/, 'return')
      const style = this.getSource('style')
      // 组件是一个对象
      let component = {}
      if (script) {
        component = new Function(script)()
      }
      if(template) {
        component.template = template
        // this.$options._base  ===  Vue
        let instance = new (this.$options._base.extend(component)) // 实例
        this.$refs.ShowBox.appendChild(instance.$mount().$el) // 挂载
      }
      if(style) {
        let element = document.createElement('style')
        element.type = 'text/css'
        element.innerText = style
        document.body.appendChild(element)
      }
      console.log(component);
    },
  },
}
</script>

<style lang="less" scoped>
.show {
  position: absolute;
  left: 50%;
  top: 0;
  width: 50%;
}
</style>
